package org.example.springsecurity0317.config;

import org.example.springsecurity0317.filter.JwtFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class SecurityConfig {
    @Autowired
    JwtFilter jwtFilter;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        /*http.csrf().disable().authorizeHttpRequests(auth->auth
                        .requestMatchers("/userlogin.html").permitAll()//允许所有人访问登录页
                        .requestMatchers("/login").permitAll()
                        //.requestMatchers("/hello").permitAll()//放行hello接口
                        .anyRequest().authenticated()//其他请求需要认证
        ).formLogin(login->login
                .loginPage("/userlogin.html")//指定自定义的登录页
                .loginProcessingUrl("/loginxxx").permitAll()//指定springsecurity处理登录请求的url,login
        );*/

        http.csrf(csrf -> csrf.disable())
                .authorizeHttpRequests(auth -> auth
                        /*.requestMatchers("/userlogin.html").permitAll()
                        .requestMatchers("/userdetail.html").permitAll()//允许所有人访问登录页
                        .requestMatchers("/hello").permitAll()//放行hello接口*/
                        .requestMatchers("/api/login").permitAll()
                        .requestMatchers("/api/**").authenticated()
                        .anyRequest().permitAll()//其他请求都放行
                ).sessionManagement(session -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
        ;
        return http.build();//用build方法构造链
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration auth) throws Exception {
        return auth.getAuthenticationManager();
    }
}
